package io.github.loan.common.util;

import java.security.MessageDigest;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

/**
 * 加密工具
 * @author Andone
 *
 */
@Component("encryptUtil")
public class EncryptUtil {
	
	@Resource
	private RegexUtil regexUtil=new RegexUtil();
	/**
	 * md5加密
	 */
	public String md5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 再次加密
	 *  明文:
	 * 32位随机数$md5$整体加密后的字符串
	 * 
	 * MD5加密:(32位随机数$md5$11111))
	 * 
	 * 密文:32位随机数$md5$  MD5加密:(32位随机数$md5$11111))
	 *  */
	public String encryptString(String password){
		String randStr=this.regexUtil.randString(32);
		System.out.println(randStr);
		String md5Str=this.md5(randStr+"$MD5$"+password);
		System.out.println(md5Str);
		return randStr+"$MD5$"+md5Str;
	}
	
	/**
	 * 解密
	 * @param args
	 */
	public boolean checkPassword(String encryptStr,String password){
		/*官方字符串中必须有$*/
		if(encryptStr.indexOf("$")==-1){
			return false;
		}
		String[] encryptStrs=encryptStr.split("\\$");
		String md5Str=encryptStrs[0]+"$"+encryptStrs[1]+"$"+password;
		md5Str=encryptStrs[0]+"$"+encryptStrs[1]+"$"+this.md5(md5Str);
		return md5Str.equalsIgnoreCase(encryptStr);
	}
	public static void main(String[] args) {
		EncryptUtil encryptUtil=new EncryptUtil();
		System.out.println("---"+encryptUtil.md5("111111"));
		System.out.println(encryptUtil.encryptString("111111"));
		String encryptStr="PxuzzVYH6VhKjYpoSlEGgpMczQi3t9Sl$MD5$C09CF3B3CB72152BFE7F7BAD1C346E39";
		String password="111111";
		System.out.println(encryptUtil.checkPassword(encryptStr, password));
	}
}
